package com.yupi.yupicturebackend.manager.upload;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.yupi.yupicturebackend.config.CosClientConfig;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.manager.CosManager;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 图片上传模板
 */
@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片到COS
     *
     * @param inputSource
     * @param uploadPathPrefix
     * @return
     */
    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        //校验图片参数
        validPicture(inputSource);
        //组合上传路径信息 请求头+操作时间+uuid+文件名后缀
        String uuid = RandomUtil.randomString(16);
        String originFilename = getOriginFilename(inputSource);
        String fileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originFilename));
        String filePath = String.format("%s/%s", uploadPathPrefix, fileName);
        //上传信息到COS
        File file = null;
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        try {
            file = File.createTempFile(filePath, null);
            processFile(inputSource, file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(filePath, file);
//            返回原图信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
//            返回压缩后的图片信息
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            CIObject ciObject = objectList.get(0);
            //缩略图默认等于压缩图
            CIObject thumbnailObject = ciObject;
            if (objectList.size() > 1) {
                thumbnailObject = objectList.get(1);
            }
            if (objectList.size() >= 1) {
                //返回压缩后的返回信息
                return this.buildResult(originFilename, ciObject, thumbnailObject,imageInfo);
            }
//          封装图片返回信息
            buildResult(originFilename, filePath, new UploadPictureResult(), imageInfo);
        } catch (IOException e) {
            log.info("图片存储上传失败", e);
            e.printStackTrace();
        } finally {
            if (file != null) {
                file.delete();
            }
            if (file == null) {
                log.error("临时文件不纯在, filePath = {}", filePath);
            }
        }
        //返回上传结果
        return uploadPictureResult;
    }

    /**
     * 压缩后的图片封装
     */
    private UploadPictureResult buildResult(String originFilename, CIObject ciObject, CIObject thumbnailObject,ImageInfo imageInfo) {
        //计算宽高比
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        double round = NumberUtil.round(ciObject.getWidth() * 1.0 / ciObject.getHeight(), 2).doubleValue();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + ciObject.getKey());
        uploadPictureResult.setPicSize(ciObject.getSize().longValue());
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        uploadPictureResult.setPicWidth(ciObject.getWidth());
        uploadPictureResult.setPicHeight(ciObject.getHeight());
        uploadPictureResult.setPicScale(round);
        uploadPictureResult.setPicFormat(ciObject.getFormat());
        uploadPictureResult.setPicColor(imageInfo.getAve());
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailObject.getKey());
        return uploadPictureResult;
    }

    /**
     * 原始图片的封装
     *
     * @param fileName
     * @param filePath
     * @param uploadPictureResult
     * @param imageInfo
     */
    private void buildResult(String fileName, String filePath, UploadPictureResult uploadPictureResult, ImageInfo imageInfo) {
        //计算宽高比
        double round = NumberUtil.round(imageInfo.getWidth() * 1.0 / imageInfo.getHeight(), 2).doubleValue();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + filePath);
        uploadPictureResult.setPicName(fileName);
        uploadPictureResult.setPicWidth(imageInfo.getWidth());
        uploadPictureResult.setPicHeight(imageInfo.getHeight());
        uploadPictureResult.setPicScale(round);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        uploadPictureResult.setPicColor(imageInfo.getAve());
    }

    protected abstract String getOriginFilename(Object inputSource);

    protected abstract void processFile(Object inputSource, File file);

    protected abstract void validPicture(Object inputSource);
}
